package xworker;

import org.xmeta.Category;
import org.xmeta.Thing;
import org.xmeta.ThingManager;
import org.xmeta.World;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class GenerateReflectconfig {
    public static void checkThing(Thing thing, List<String> javaList){
        if(thing.getThingName().equals("JavaAction")){
            String outerClassName = thing.getStringBlankAsNull("outerClassName");
            if(outerClassName != null && !javaList.contains(outerClassName)){
                javaList.add(outerClassName);
            }
        }else{
            for(Thing child : thing.getChilds()){
                checkThing(child, javaList);
            }
        }
    }


    public static void main(String[] args){
        try{
            World world = World.getInstance();
            world.init("./xworker/");
            world.addFileThingManager("resources", new File("./src/main/resources/"), false, false);

            ThingManager resourceManager = world.getThingManager("resources");
            Thread.sleep(10000);
            List<String> javaList = new ArrayList<>();
            for(ThingManager thingManager : world.getThingManagers()){
                if(thingManager.getName().equals("resources")){
                    continue;
                }

                System.out.println(thingManager.getName());
                Iterator<Thing> iter = thingManager.iterator(null, true);
                while(iter.hasNext()){
                    Thing thing = iter.next();
                    System.out.println(thing.getMetadata().getPath());
                    checkThing(thing, javaList);
                }
            }

            System.out.println(javaList);

            FileOutputStream fout = new FileOutputStream("./src/main/resources/META-INF/substrate/config/reflectionconfig.json");
            fout.write("[\n".getBytes());
            for(int i=0;i<javaList.size(); i++){
                String name = javaList.get(i);
                fout.write(("  {\n    \"name\":\"" + name + "\",\n").getBytes());
                fout.write(("    \"allDeclaredConstructors\" : true,\n").getBytes());
                fout.write(("    \"allPublicConstructors\" : true,\n" +
                        "    \"allDeclaredFields\" : true,\n" +
                        "    \"allPublicFields\" : true,\n" +
                        "    \"allDeclaredMethods\" : true,\n" +
                        "    \"allPublicMethods\" : true\n  }").getBytes());
                if(i < javaList.size() - 1){
                    fout.write(",\n".getBytes());
                }else{
                    fout.write("\n".getBytes());
                }
            }
            fout.write("]".getBytes());

        }catch(Exception e){
            e.printStackTrace();
        }
    }
}
